package servlet.admin;

import com.alibaba.fastjson.JSONObject;
import entity.Borrow_card;

import service.admin.CardAddService;
import service.admin.impl.CardAddServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * CardAddServlet
 *
 * @author lenovo
 * @since 2023/9/4
 */
@WebServlet("/admin/cardAdd")
public class CardAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    //引入服务层
    CardAddService service = new CardAddServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        // 获取参数
        String reader = req.getParameter("reader");
        String password = req.getParameter("password");
        String rule_id = req.getParameter("rule_id");
        String status = req.getParameter("status");
        String code = "1";
        String msg = "error";// 参数不能为空
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonData = new JSONObject();
        //创建对象
        Borrow_card borrow_card = new Borrow_card(password,reader,Integer.valueOf(rule_id),Integer.valueOf(status));
        if(reader == null || password == null || rule_id == null || rule_id == null || status == null) {
            code = "1";
            msg = "值不能为空";
        }else{
            int result = service.add(borrow_card);
            int id = service.getId(borrow_card);
            if (result > 0 && id != 0){
                code = "0";
                msg = "添加成功";
                jsonData.put("id",id);
            }else{
                code = "1";
                msg = "执行失败";
            }
        }
        jsonObject.put("code", code);
        jsonObject.put("msg", msg);
        jsonObject.put("data",jsonData.toJSONString());
        PrintWriter out = resp.getWriter();
        out.print(jsonObject.toJSONString());
        out.flush();
        out.close();
    }
}
